package com.demo.jingxi.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.jingxi.common.Result;
import com.demo.jingxi.pojo.TbProduct;
import com.demo.jingxi.service.ITbProductService;
import com.demo.jingxi.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author aoyuan
 * @since 2023-09-24
 */
@RestController
@RequestMapping("/product")
public class TbProductController {
    @Autowired
    private ITbProductService iTbProductService;
    @GetMapping("/list")
    public Result<Map<String,Object>> getUserList(@RequestParam(value = "name", required = false) String name,
                                                  @RequestParam(value = "type", required = false) Integer type,
                                                  @RequestParam(value = "pageNo") Long pageNo,
                                                  @RequestParam(value = "pageSize") Long pageSize){
        String decodedName = decodeParameter(name);

        LambdaQueryWrapper<TbProduct> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.hasLength(decodedName), TbProduct::getName, decodedName.trim());
        wrapper.like(type != null, TbProduct::getType, type);

        Page<TbProduct> page = new Page<>(pageNo, pageSize);
        iTbProductService.page(page, wrapper);

        Map<String,Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    // 解码参数
    private String decodeParameter(String parameter) {
        if (parameter != null && !parameter.isEmpty()) {
            try {
                return URLDecoder.decode(parameter, "UTF-8");
            } catch (Exception e) {
                // 解码失败则返回原始参数值
            }
        }
        return parameter;
    }
    @PostMapping
    public Result<?> addType(@RequestBody TbProduct tbProduct){
        iTbProductService.save(tbProduct);
        return Result.success("新增角色成功");
    }
    @PutMapping
    public Result<?> update(@RequestBody TbProduct tbProduct){
        iTbProductService.updateById(tbProduct);
        return Result.success("修改角色成功");
    }

    @GetMapping("/{id}")
    public Result<TbProduct> getTypeById(@PathVariable("id") Integer id){
        TbProduct tbProduct = iTbProductService.getById(id);
        return Result.success(tbProduct);
    }

    @DeleteMapping("/{id}")
    public Result<TbProduct> deleteRoleById(@PathVariable("id") Integer id){
        iTbProductService.removeById(id);
        return Result.success("删除角色成功");
    }
}
